//
//  NetResponse.cpp
//  TestCpp
//
//  Created by Paladin on 13-3-11.
//
//

#include "NetResponse.h"
#include "../cocos2dx/support/zip_support/ZipUtils.h"

int CNetResponse::response(CCNode *sender, void *data)
{
    mHttpStatus = 0;
    mResponseData = (CCHttpResponse*)data;
    if (!mResponseData)
    {
        CCLOG("Response Data is empty!!!");
        mHttpStatus = -999; // data is NULL
        return mHttpStatus;
    }
    // You can get original request type from: response->request->reqType
    if (0 != strlen(mResponseData->getHttpRequest()->getTag()))
    {
        CCLog("%s completed", mResponseData->getHttpRequest()->getTag());
    }
    mHttpStatus = mResponseData->getResponseCode();
    // TODO::调试信息
    CCLOG("HTTP Status Code: %d, tag = %s", mHttpStatus, mResponseData->getHttpRequest()->getTag());
    // 服务器响应成功, 则返回当前服务器的状态
    if (mResponseData->isSucceed())
    {
        parseJsonValue();
        return mServerStatus; // 服务器状态
    }
    else // 网络问题，需要处理的问题，比如公共提示机制,供用户进行重试
    {
        // TODO::失败处理....
        CCLog("response failed");
        CCLog("error buffer: %s", mResponseData->getErrorBuffer());
        return mHttpStatus;
    }
    return 0;
}

void CNetResponse::parseJsonValue()
{
    bool ret = false;
    Json::Reader reader;
    std::string str = "";
    
    std::vector<char> *buffer = mResponseData->getResponseData();
    if (NULL != buffer && buffer->size() > 0)
    {
        str.insert(str.begin(), buffer->begin(), buffer->end());
        printf("Http Test, dump data: %s", str.c_str());
        // 这里是否可以设计为根据一个Json中的字段来表达数据是否需要进行解压，解密等操作?
        /*
            TODO::
            ZipUtils::ccInflateMemory(zlib_comperss_data_in, zlib_compress_data_len_in, uncompress_data_out);
        */
        ret = reader.parse(str, root);
        if (ret)
        {
            mServerStatus = root["SvrRet"].asInt();
        }
        else
        {
            CCLOG("Json::reader->parse failed. ErrorMessage = %s", reader.getFormatedErrorMessages().c_str());
        }
        return ;
    }
    else
    {
        // TODO::针对服务器错误的公共处理
    }
}

void CNetResponse::uncompress(void *data)
{
    //TODO::
}

void CNetResponse::decryption(void *data)
{
    //TODO::
}